﻿using ExamRoomAllocationManagement.Dao;
using System.Text.Json;
using Xmu.Stores.Models;

namespace ExamRoomAllocationManagement.Services
{
    public class RegistrationService : ISingletonDependency
    {
        private IServiceProvider serviceProvider;
        private Repositories repo;
        public RegistrationService(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
            repo = serviceProvider.CreateScope().ServiceProvider.GetRequiredService<Repositories>();
        }

        public (object registions, object msg) GetAllRegistrations()
        {
            return (repo.Registrations.ToList(), "ok");
        }

        public (object registions, object msg) GetRegistrations(int pageIndex, int pageSize)
        {
            return (repo.Registrations.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(), "ok");
        }

        public (bool success, string msg) AddRegistration(Registration registration)
        {
            Exam? exam = repo.Exams.FirstOrDefault(e => e.ExamId == registration.ExamID);
            if (exam == null) { return (false, "考试不存在"); }

            

            registration.Exam = exam;

            string json = JsonSerializer.Serialize(registration, new JsonSerializerOptions
            {
                WriteIndented = true // 如果希望输出格式化的 JSON，可以设置 WriteIndented 为 true
            });
            Console.WriteLine("registration:" + json);

            repo.Registrations.Add(registration);
            repo.DbContex.SaveChanges();
            return (true, "ok");
        }

        public (bool success, object msg) EmptyRegistration()
        {
            repo.Registrations.RemoveRange(repo.Registrations);
            repo.DbContex.SaveChanges();
            return (true, "ok");
        }
    }
}